Home:ALL Converter>How to update fields in a MongoDB collection if certain conditions met between two collections?

How to update fields in a MongoDB collection if certain conditions met between two collections?

Ask Time:2022-05-05T10:39:22         Author:Victor Guidi

Json Formatter

What am I doing?

So I am trying to update two fields in my MongoDB collection. The collection name is mydata and looks like this:

{
  id: 123,
  name: "John",
  class: "A-100",
  class_id: "", <-- Need to update this field,
  class_type: "", <-- Need to update this field
}

What do I want to do?

I have another collection that is older, but it contains two fields that I need that I do not have in my current collection. But they both have the id field that corresponds. This is how it looks like the other collection:

{
  id: 123,
  name: "John",
  class: "A-100",
  class_id: 235, <-- Field That I need,
  class_type: "Math" <-- Field That I need
}

What have I done so far?

I started an aggregate function that starts with a $lookup then $unwind then $match then $project. Looks like this:

db.mydata.aggregate([
  {
    $lookup: {
      from: "old_collection",
      localField: "id",
      foreignField: "id",
      as: "newData"
    }
  },
  {
    $unwind: "newData"
  },
  {
    $match: {"class": "A-100"} 
  },
  {
    $project: {
     _id: 0,
     "id": "$newData.id",
     "class_id": "$newData.class_id",
     "class_type": "$newData.class_type"
   }
  },
Need help here to update mydata collection in the 
fields that I pointed in the top
])

In summary

What I am trying to do is: If two objects from different collections have the same Id then pick the keys from the second object and update the keys in the first object.

Is there a way to do that in MongoDB?

Thanks.

Author:Victor Guidi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72121333/how-to-update-fields-in-a-mongodb-collection-if-certain-conditions-met-between-t
yy